#include "rot_adc.h"

void adc_init(void) {

  /* Disable internal pull-up of pin PC0 */
  PORTC &= ~(1<<PC0);
  DDRC &= ~(1<<PC0);
  /* Setting the reference to AREF */
  ADMUX &= ~((1<<REFS1)|(1<<REFS0)); 
  /* 128 pre-scaler, activate   */
  ADCSRA |= _BV(ADEN) | _BV(ADPS2) | _BV(ADPS1) | _BV(ADPS0) | _BV(ADSC);
  /* Wait for the ADC to return a sample */
  loop_until_bit_is_clear(ADCSRA, ADSC);

}

unsigned short adc_read(unsigned char pin) {
  
  unsigned char l, h, r;
  
  r = (ADMUX & 0xf0) | (pin & 0x0f);
  ADMUX = r; /* select the input channel */
  ADCSRA |= _BV(ADSC);
  loop_until_bit_is_clear(ADCSRA, ADSC);
  
  /* must read the low ADC byte before the high ADC byte */
  l = ADCL;
  h = ADCH;
  
  return ((unsigned short)h << 8) | l;
}
